import message from "./message"

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "D+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  }
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    )
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      )
    }
  }
  return fmt
}

const myfunction = {
  price_num: 100,
  wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
  phoneCheck(value) {
    if (!value) {
      return false
    }

    value = this.trim(value)
    if (value === "") {
      return false
    }

    return /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)
  },
  mailCheck(value) {
    if (!value) {
      return false
    }

    value = this.trim(value)
    if (value === "") {
      return false
    }

    let reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    return reg.test(value)
  },
  isWeiXin() {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      return true
    } else {
      return false
    }
  },
  /* 去前后空格 */
  trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "")
  },
  uuid() {
    var s = []
    var hexDigits = "0123456789abcdef"
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = "4" // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-"

    const dt = Number(new Date())
    var uuid = s.join("") + "-" + dt
    return uuid
  },

  random(min, max) {
    return Math.floor(Math.random() * (max - min)) + min
  },

  isArray(o) {
    return Object.prototype.toString.call(o) == "[object Array]"
  },
  isObject(val) {
    return Object.prototype.toString.call(val) === "[object Object]"
  },
  isString(val) {
    return Object.prototype.toString.call(val) == "[object String]"
  },
  isNumber(val) {
    // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除，
    if (val === "" || val == null) {
      return false
    }
    if (!isNaN(val)) {
      //对于空数组和只有一个数值成员的数组或全是数字组成的字符串，isNaN返回false，例如：'123'、[]、[2]、['123'],isNaN返回false,
      //所以如果不需要val包含这些特殊情况，则这个判断改写为if(!isNaN(val) && typeof val === 'number' )
      return true
    } else {
      return false
    }
  },
  isDate(val) {
    return Object.prototype.toString.call(val) === "[object Date]"
  },
  clone(Obj) {
    var buf
    if (Obj instanceof Array) {
      buf = []
      var i = Obj.length
      while (i--) {
        buf[i] = this.clone(Obj[i])
      }
      return buf
    } else if (Obj instanceof Object) {
      buf = {}
      for (var k in Obj) {
        buf[k] = this.clone(Obj[k])
      }
      return buf
    } else {
      return Obj
    }
  },

  priceFormat(val) {
    return Math.round(val * this.price_num) / this.price_num
  },

  //图片上传
  beforeUpload(file) {
    const isJPG = file.type === "image/jpeg"
    const isJPEG = file.type === "image/jpeg"
    const isGIF = file.type === "image/gif"
    const isPNG = file.type === "image/png"

    if (!isJPG && !isJPEG && !isGIF && !isPNG) {
      message.error("You can only upload image file!")
      return false
    }
    return true
  },
  UploadFileOne(info, cb) {
    const status = info.file.status
    if (status === "done") {
      const response = info.file.response
      if (response.code !== 1) {
        message.error(`上传文件 ${info.file.name} 失败, ${response.message}`)
        return
      }
      try {
        cb(response.data)
        message.success(`${info.file.name} 上传成功.`)
      } catch (error) {
        message.success(`${info.file.name} 上传成功， 回掉参数错误`)
      }
    }
  },

  //数组删除一个元素
  deleteItem(arr, index) {
    arr.splice(index, 1)
  },

  //初始化编辑对象
  // 处理 that 下  分层 keyArr 下 的 item 和 itemHide 的值
  initEdit(that, keyArr, data) {
    if (!data || Object.prototype.toString.call(data) !== "[object Object]")
      return

    let tmpItem = that,
      flag = false
    for (let jj in keyArr) {
      if (Object.prototype.toString.call(tmpItem) == "[object Object]") {
        if (tmpItem[keyArr[jj]]) {
          tmpItem = tmpItem[keyArr[jj]]
          flag = true
          continue
        }
      }

      if (Object.prototype.toString.call(tmpItem) == "[object Array]") {
        for (let index in tmpItem) {
          if (!tmpItem[index].key) continue

          if (tmpItem[index].key == keyArr[jj]) {
            tmpItem = tmpItem[index]
            flag = true
            break
          }
        }
        continue
      }

      flag = false
      break
    }
    if (!flag) return

    if (Object.prototype.hasOwnProperty.call(tmpItem, "itemHide")) {
      let item = tmpItem.itemHide
      for (let ii in data) {
        if (Object.prototype.hasOwnProperty.call(item, ii)) {
          that.$set(item, ii, data[ii])
        }
      }
    }

    if (Object.prototype.hasOwnProperty.call(tmpItem, "item")) {
      let item = tmpItem.item
      for (let ii in item) {
        let tmpFir = item[ii]
        if (tmpFir.type == "space") {
          if (tmpFir.space)
            for (let jj in tmpFir.space) {
              let tmpKey = tmpFir.space[jj].key
              if (Object.prototype.hasOwnProperty.call(data, tmpKey)) {
                that.$set(tmpFir.space[jj], "value", data[tmpKey])
              }
            }
          continue
        }
        if (Object.prototype.hasOwnProperty.call(data, ii)) {
          that.$set(tmpFir, "value", data[ii])
        }
      }
    }
  },
  initItem(that, keyArr, data) {
    if (!data || Object.prototype.toString.call(data) !== "[object Object]")
      return

    let tmpItem = that,
      flag = false

    for (let jj in keyArr) {
      if (Object.prototype.toString.call(tmpItem) == "[object Object]") {
        if (tmpItem[keyArr[jj]]) {
          tmpItem = tmpItem[keyArr[jj]]
          flag = true
          continue
        }
      }
      if (Object.prototype.toString.call(tmpItem) == "[object Array]") {
        for (let index in tmpItem) {
          if (!tmpItem[index].key) continue

          if (tmpItem[index].key == keyArr[jj]) {
            tmpItem = tmpItem[index]
            flag = true
            break
          }
        }
        continue
      }

      flag = false
      break
    }

    if (!flag) return

    if (Object.prototype.toString.call(data) !== "[object Object]") return

    for (let ii in data) {
      that.$set(tmpItem, ii, data[ii])
    }
  },
}

export default myfunction
